/**
 * 构建树形结构
 * @param list 扁平数据列表
 * @param idKey ID字段名
 * @param parentKey 父ID字段名
 * @param childrenKey 子节点字段名
 * @returns 树形结构数据
 */
export function buildTree<T extends Record<string, any>>(
  list: T[],
  idKey: keyof T = 'id' as keyof T,
  parentKey: keyof T = 'fid' as keyof T,
  childrenKey: string = 'children'
): T[] {
  const map: Record<any, T> = {};
  const roots: T[] = [];
  
  // 创建节点映射
  list.forEach(item => {
    map[item[idKey]] = { ...item, [childrenKey]: [] };
  });
  
  // 构建父子关系
  list.forEach(item => {
    const parentId = item[parentKey];
    if (parentId && map[parentId]) {
      map[parentId][childrenKey].push(map[item[idKey]]);
    } else {
      roots.push(map[item[idKey]]);
    }
  });
  
  return roots;
}

/**
 * 扁平化树形结构
 * @param tree 树形数据
 * @param childrenKey 子节点字段名
 * @returns 扁平化数据
 */
export function flattenTree<T extends Record<string, any>>(
  tree: T[],
  childrenKey: string = 'children'
): T[] {
  const result: T[] = [];
  
  function traverse(nodes: T[]) {
    nodes.forEach(node => {
      const children = node[childrenKey] || [];
      const { [childrenKey]: _, ...nodeWithoutChildren } = node;
      result.push(nodeWithoutChildren as T);
      if (children.length > 0) {
        traverse(children);
      }
    });
  }
  
  traverse(tree);
  return result;
}

/**
 * 查找树形结构中的节点
 * @param tree 树形数据
 * @param predicate 查找条件函数
 * @param childrenKey 子节点字段名
 * @returns 找到的节点或null
 */
export function findTreeNode<T extends Record<string, any>>(
  tree: T[],
  predicate: (node: T) => boolean,
  childrenKey: string = 'children'
): T | null {
  for (const node of tree) {
    if (predicate(node)) {
      return node;
    }
    const children = node[childrenKey] || [];
    if (children.length > 0) {
      const found = findTreeNode(children, predicate, childrenKey);
      if (found) {
        return found;
      }
    }
  }
  return null;
} 